package com.nl.controller.common.service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.util.BaseResult;
import com.nl.controller.common.util.HttpClientUtil;
import com.nl.controller.sms5g.bean.BdResult;
import com.nl.controller.sms5g.bean.DoubleUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.interceptor.SysContext;
import com.nl.controller.common.mapper.CommonMapper;
import com.nl.controller.web.bean.SmsMgrGovernmentInfo;
import com.nl.controller.web.bean.SmsMgrInfo;
import com.nl.controller.web.bean.SmsOperLog;
import com.nl.controller.web.bean.SmsUsers;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;

@Service
@Slf4j
public class CommonService {

    @Autowired
    private CommonMapper commonMapper;




    public static String httpPostWithJson(String url, JSONObject jsonParam)
            throws Exception {
        DefaultHttpClient httpclient = null;
        HttpPost httpPost = null;
        HttpResponse response = null;
        org.apache.http.HttpEntity entity = null;
        String result = "";
        try {
            httpclient = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            // 解决中文乱码问题
            StringEntity entityParam = new StringEntity(jsonParam.toString(),"utf-8");
            entityParam.setContentEncoding("UTF-8");
            entityParam.setContentType("application/json");
            httpPost.setEntity(entityParam);
            // 设置连接超时时间
            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),
                    100000);
            // 设置读数据超时时间
            HttpConnectionParams.setSoTimeout(httpclient.getParams(), 100000);
            response = httpclient.execute(httpPost);
            entity = response.getEntity();
            if (null != entity) {
                byte[] bytes = EntityUtils.toByteArray(entity);
                result = new String(bytes, "UTF-8");
            }
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != httpclient) {
                httpclient.getConnectionManager().shutdown();
            }
        }
    }

    /**
     * 创建日志信息
     *
     * @param type   类型 0登录  1忘记密码  2新增  3修改  4查询 5删除 6接口  7导出
     * @param remark 操作说明，如新增短信项目
     * @param result 操作结果，0成功1失败
     * @param menu   填写具体二级菜单名称
     */
    public void createSmsOperLog(String type, String id,String remark, String result, String menu) {
        try {
            HttpSession session = SysContext.getRequest().getSession();
            SmsOperLog smsOperLog = new SmsOperLog();
            SmsUsers user = (SmsUsers) session.getAttribute("user");
            if (user != null) {
            	smsOperLog.setMgrId(id);
                smsOperLog.setMsisdn(user.getMsisdn());
                smsOperLog.setUserName(user.getUserName());
                smsOperLog.setDuty(user.getDuty());
                smsOperLog.setGroupName(this.getGroupName(user));
                smsOperLog.setFunctionName(menu);
                smsOperLog.setType(type);
                smsOperLog.setRemark(remark);
                smsOperLog.setResult(result);
                smsOperLog.setOperCityId(user.getCityId());
                log.info("smsOperLog:{}", smsOperLog.toString());
                commonMapper.createSmsOperLog(smsOperLog);
            }else if ("6".equals(type)) {
            	smsOperLog.setType(type);
            	smsOperLog.setRemark(remark);
            	smsOperLog.setResult(result);
			}
        } catch (Exception e) {
            e.printStackTrace();
            log.error("日志插入异常1，不抛出继续在走完流程");
        }
    }

    /**
     * 创建日志信息,采集登陆日志
     *
     * @param user   登录对象实体
     * @param type   类型 0登录  1忘记密码  2新增  3修改  4查询 5删除 6接口
     * @param remark 操作说明，如新增短信项目
     * @param result 操作结果，0成功1失败
     * @param menu   填写具体二级菜单名称
     */
    public void createSmsOperLog(SmsUsers user,
                                 String type, String remark, String result, String menu) {
        try {
        	
            SmsOperLog smsOperLog = new SmsOperLog();
            smsOperLog.setMsisdn(user.getMsisdn());
            smsOperLog.setUserName(user.getUserName());
            smsOperLog.setDuty(user.getDuty());
            smsOperLog.setGroupName(this.getGroupName(user));
            smsOperLog.setFunctionName(menu);
            smsOperLog.setType(type);
            smsOperLog.setRemark(remark);
            smsOperLog.setResult(result);
            smsOperLog.setOperCityId(user.getCityId());
            log.info("smsOperLog:{}", smsOperLog.toString());
            commonMapper.createSmsOperLog(smsOperLog);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("日志插入异常2，不抛出继续在走完流程");
        }
    }

    /**
     * 获取项目名称
     *
     * @param user 登录对象实体
     * @return 归属组，如级别是省公司管理员，归属省公司，
     * 如地市管理员则归属具体地市，如项目经理则归属具体什么项目，可能多个项目
     */
    private String getGroupName(SmsUsers user) {
        String groupName = "";
        if ("0".equals(user.getDuty())) {
            groupName = "省公司管理员";
        } else if ("1".equals(user.getDuty())) {
            groupName = "地市管理员";
        } else if ("2".equals(user.getDuty())) {
            groupName = "区县管理员";
        } else if ("3".equals(user.getDuty())) {
        	groupName = "项目管理员";
            /*List<String> list = commonMapper.getMgrName(user.getMgrId());
            for (String str : list) {
                groupName += str;
            }*/
        } else {
            groupName = "系统管理员";
        }
        return groupName;
    }

    @SystemServiceLog(description = "获取模板审核需要发送的管理员号码", value = false)
    public String[] templateNotice(String id) {
        String msisdn = "";
        try {
            msisdn = commonMapper.templateNotice(id);
            log.info("获取模板审核需要发送的管理员号码");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取模板审核需要发送的管理员号码");
        }
        return msisdn.split(",");
    }
    @SystemServiceLog(description = "项目名称联想", value = false)
    public List<SmsMgrInfo> selectMgrNameLike(String key,String cityId, String countyId){
        List<SmsMgrInfo> list= commonMapper.selectMgrNameLike(key,cityId, countyId);
        return list;
    }
      
    @SystemServiceLog(description = "项目名称联想精准政务", value = false)
    public List<SmsMgrGovernmentInfo> selectMgrNameLikeG(String key){
        List<SmsMgrGovernmentInfo> list= commonMapper.selectMgrNameLikeG(key);
        return list;
    }
    
    /**
     * 创建修改操作日志信息
     *
     * @param type   类型 0登录  1忘记密码  2新增  3修改  4查询 5删除 6接口
     * @param remark 操作说明，如新增短信项目
     * @param result 操作结果，0成功1失败
     * @param menu   填写具体二级菜单名称
     */
    public void createSmsUpdateOperLog(String type, String mgrId, String remark, String result, String menu, String seqId) {
        try {
            HttpSession session = SysContext.getRequest().getSession();
            SmsOperLog smsOperLog = new SmsOperLog();
            SmsUsers user = (SmsUsers) session.getAttribute("user");
            if (user != null) {
            	smsOperLog.setMgrId(mgrId);
                smsOperLog.setMsisdn(user.getMsisdn());
                smsOperLog.setUserName(user.getUserName());
                smsOperLog.setDuty(user.getDuty());
                smsOperLog.setGroupName(this.getGroupName(user));
                smsOperLog.setFunctionName(menu);
                smsOperLog.setType(type);
                smsOperLog.setRemark(remark);
                smsOperLog.setResult(result);
                smsOperLog.setSeqId(seqId);
                smsOperLog.setOperCityId(user.getCityId());
                log.info("smsOperLog:{}", smsOperLog.toString());
                commonMapper.createSmsUpdateOperLog(smsOperLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("日志插入异常1，不抛出继续在走完流程");
        }
    }

    public static String BdToGPS(String lngAndLat) throws UnsupportedEncodingException {
        String[] split = lngAndLat.split(",");
        String lng = split[0];
        String lat = split[1];
        String url = "http://api.map.baidu.com/ag/coord/convert";
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("from", "0");
        querys.put("to", "4");
        querys.put("x", lng);
        querys.put("y", lat);
        BaseResult<String> sendGet = HttpClientUtil.sendGet(url, querys, "utf-8", null);
        if ("0".equals(sendGet.getRetCode())) {
            BdResult data =  JSONObject.parseObject(sendGet.getData(), BdResult.class) ;
            if ("0".equals(data.getError())) {
                String x = new String(Base64Utils.decode(data.getX().getBytes()), "utf-8");
                String y = new String(Base64Utils.decode(data.getY().getBytes()), "utf-8");
                Double lngGPS = DoubleUtil.sub(DoubleUtil.mul(2.0, Double.parseDouble(lng)),Double.parseDouble(x));
                Double latGPS =DoubleUtil.sub(DoubleUtil.mul(2.0, Double.parseDouble(lat)),Double.parseDouble(y));
                return lngGPS.toString()+","+latGPS.toString();
            }
        }
        return lng+","+lat;
    }
}
